package com.yhh.Entity;

import com.yhh.Exceptions.InstructionException;

import java.io.*;
import java.net.Socket;
import java.util.HashSet;
import java.util.Map;

public abstract class Command {
    /**
     * 存储该指令的合法指令
     */
    protected HashSet<String> command = new HashSet<>();

    /**
     * 处理参数
     * @param args 传入的参数
     * @throws Exception
     */
    public abstract void handlerParameter(Map<String, String> args) throws Exception;


    /**
     * 检查参数指令是否合法
     * @param args
     * @return
     * @throws Exception
     */
    public abstract boolean check(Map<String, String> args) throws Exception;

    /**
     * 检查参数合法性
     * @param args
     * @throws InstructionException
     */
    public void checkParameter(Map<String, String> args) throws InstructionException {
        for (Map.Entry<String, String> entry : args.entrySet()) {
            String k = entry.getKey();
            if (!command.contains(k)) throw new InstructionException("指令发生异常!" + k + "为不识别的指令。", k);
        }
    }

    protected BufferedReader br = null;

    protected BufferedWriter bw = null;

    protected Socket socket = null;

    StringBuilder msg = new StringBuilder();

    protected Command(Socket socket) {
        try {
            command.add("start");
            this.socket = socket;
            this.br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            this.bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 封装发送操作函数，增加可读性
     * @return
     */
    protected void sendMsg(String s) {
        msg.append(s).append("\n");
        try {
            bw.write(msg.toString());
            //StringBuilder
            msg.delete(0, msg.length());
            // 调用flush()方法将缓冲输出
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 封装接受操作函数，增加可读性
     * @return
     */
    protected String recvMsg() {
        String msg = null;
        try {
            msg = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }
}
